package 事务操作;

import java.sql.*;
import java.util.Scanner;

/**
 * 转账：A给B转???元,SQL中不在拼接字符串
 */
public class Transaction3 {
    public static void main(String[] args) {
        String fkf = null;
        String skf = null;
        int rmb = 0;
        //接受用户输入Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入本次的转账金额：");
        rmb = sc.nextInt();
        System.out.println("请输入付款方id：");
        fkf = sc.next();
        System.out.println("请输入收款方id：");
        skf = sc.next();
        System.out.println("正在转账"+rmb+"元");
        String url = "jdbc:mysql://localhost:3306/db_jdbc_demo" +
                "?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String pass = "000000";
        Connection conn = null;
        PreparedStatement pstmt = null;
        //将Statement换成高级版

        //ResultSet省略，因为Update没有结果集

        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pass);
            //String sql1 = "update t_account set money = money - "+rmb+" where id = "+fkf ;

            String sql1 = "update t_account set money = money - ? where id = ?  " ;
            String sql2 = "update t_account set money = money + ? where id =  ? ";
            //开启事务
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql1);//预编译的Statement对象（高级版）
            //将SQL中的？ 换成具体数值
            pstmt.setInt(1,rmb);
            pstmt.setString(2,fkf);
            int i = pstmt.executeUpdate(sql1);
            //int x = 5/0;
            pstmt = conn.prepareStatement(sql2 );////预编译的Statement对象（高级版）
            //将SQL中的？ 换成具体数值
            pstmt.setInt(1,rmb);
            pstmt.setString(2,fkf);
            int j = pstmt.executeUpdate(sql1);
            if (i+j==2){
                System.out.println("转账成功！");
                conn.commit();
            }else {
                System.out.println("转账失败！");
            }

        }catch (Exception e){
            //e.printStackTrace();
            System.out.println("转账出现异常！");

            try {
                conn.rollback();
            }catch (SQLException ex){
                ex.printStackTrace();
            }
        }finally {
            try {
                pstmt.close();
                conn.close();
            }catch (SQLException e){
                e.printStackTrace();
            }

        }
    }
}
